package ilender.serialization;

import java.lang.reflect.Type;
import java.util.Date;

import com.google.gson.*;
import org.joda.time.*;
import org.joda.time.format.*;

import ilender.formatting.*;

/**Used for writing JodaTime's datetime to JSON and vice versa.*/
public class DateTimeTypeConverter implements JsonSerializer<DateTime>,JsonDeserializer<DateTime>{

	@Override
	public JsonElement serialize(DateTime src, Type srcType, JsonSerializationContext context) {
		return new JsonPrimitive(DateTimeFormatting.forJsonDateTime().print(src));
	}

	@Override
	public DateTime deserialize(JsonElement json,Type type,JsonDeserializationContext context) throws JsonParseException{
		try{
			return DateTimeFormatting.forJsonDateTime().parseDateTime(json.getAsString());
		}catch(IllegalArgumentException e){
			return null;
		}
	}
}

